import { ref } from 'vue';

export function useSSE() {
  const bufferCache = ref(null);
  const eventData = ref('');
  const error = ref(null);
  const isConnected = ref(false);

  // 解码 ArrayBuffer，处理 UTF-8 截断问题
  const decodeArrayBuffer = (arrayBuffer) => {
    if (bufferCache.value) {
      const combined = new Uint8Array(bufferCache.value.byteLength + arrayBuffer.byteLength);
      combined.set(new Uint8Array(bufferCache.value), 0);
      combined.set(new Uint8Array(arrayBuffer), bufferCache.value.byteLength);
      arrayBuffer = combined.buffer;
      bufferCache.value = null;
    }

    try {
      const decoder = new TextDecoder('utf-8');
      return decoder.decode(new Uint8Array(arrayBuffer));
    } catch (e) {
      bufferCache.value = arrayBuffer.slice(-3); // 缓存可能截断的 UTF-8 字节
      return '';
    }
  };

  // 连接 SSE 服务
  const connect = (url, params, onMessage) => {
    const requestTask = uni.request({
      url,
      method: 'GET',
      data: params,
      enableChunked: true,
      header: {
        'Accept': 'text/event-stream',
        'Content-Type': 'application/json',
      },
      success: (res) => {
        console.log('Final response:', res);
		isConnected.value = false;
      },
      fail: (err) => {
        error.value = err;
        isConnected.value = false;
      },
    });

    requestTask.onChunkReceived((res) => {
      const text = decodeArrayBuffer(res.data);
      if (text) {
        const result = text.match(/^data:\s*(.*)$/m);
        const content = result ? result[1] : text;
        eventData.value = content;
        onMessage?.(eventData.value);
      }
    });

    isConnected.value = true;
    return requestTask;
  };

  return { eventData, error, isConnected, connect };
}